package com.srwl.mytx.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.srwl.mytx.R;
import com.srwl.mytx.adapter.PhotosAdapter;
import com.srwl.mytx.domain.Message;

import java.util.List;


/**
 * 全屏大图展示
 * <p>
 * 存在的问题：为了保留缩放动画效果，需要关闭item的复用，但是关闭复用之后，item 不会被缓存，滑出可见区域，就会被杀死；
 * 重新滑回来，就会重建，重建的时候，感觉到图片加载跟不上，会出现黑边，，，
 * <p>
 * 关键还是PhotoView 使用animaTo（） 方法后，当item 复用，再使用 ainmaFrom()的时候，位置会错乱，暂时没参透 anima这两个方法，，，
 */
public class PhotosView extends FrameLayout {
    private static final String TAG = "PhotosView";
    private Context context;
    protected RecyclerView rl_photos;
    protected PhotosAdapter photosAdapter;
    private ImageView iv_blackBackGround;
    //View fl_bigPicture;
    AlphaAnimation in = new AlphaAnimation(0, 1);
    AlphaAnimation out = new AlphaAnimation(1, 0);
    private List<Message> imageMessageList;
    private boolean statusOfShowBigImage = false;
    private InteractionListener onPageChangeListener;
    //当前显示的 view
    private View snapView;
    private LinearLayoutManager linearLayoutManager;
    private boolean recyclerViewScroll = true;
    //是否设置过数据
    private boolean hadSetData = false;

    public PhotosView(Context context) {
        super(context);
        init(context);
    }

    public PhotosView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PhotosView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.frame_layout_photos, this);
        rl_photos = findViewById(R.id.rl_photos);
        rl_photos.setItemViewCacheSize(10);
        iv_blackBackGround = findViewById(R.id.img_bg_black);


    }

    public void setDate(List<Message> imageMessageList, InteractionListener onPageChangeListener) {
        hadSetData = true;
        this.imageMessageList = imageMessageList;
        this.onPageChangeListener = onPageChangeListener;
        init();
    }

    public void setCurrentSmallImageRectInfo(int position, Info info) {

    }

    private void init() {
        PagerSnapHelper snapHelper = new PagerSnapHelper() {

            @Nullable
            @Override
            public View findSnapView(RecyclerView.LayoutManager layoutManager) {
                Log.d(TAG, "findSnapView: 获取页面当前显示的页面");
                snapView = super.findSnapView(layoutManager);
                return snapView;
            }

            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                int targetSnapPosition = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                Log.d(TAG, "onPageSelected:页面切换了 position ：" + targetSnapPosition);
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageChange(targetSnapPosition);
                }
                return targetSnapPosition;
            }
        };

        snapHelper.attachToRecyclerView(rl_photos);
        photosAdapter = new PhotosAdapter(context, imageMessageList, new PhotosAdapter.OnClickListener() {
            @Override
            public Info onGetImageRectInfo(int position) {
                recyclerViewScroll = false;
                if (onPageChangeListener != null) {
                    Info info = onPageChangeListener.onGetImageRectInfo(position);
                    hideBigImage();
                    return info;
                }

                hideBigImage();
                return null;


            }

        });
        linearLayoutManager = new LinearLayoutManager(context) {

            @Override
            public boolean canScrollVertically() {
                return recyclerViewScroll;
            }
        };

        rl_photos.setLayoutManager(linearLayoutManager);
        rl_photos.setAdapter(photosAdapter);

        //大图黑色背景显示隐藏 持续时间
        in.setDuration(400);
        in.setFillAfter(true);
        out.setDuration(400);
        out.setFillAfter(true);
        out.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                iv_blackBackGround.setVisibility(View.INVISIBLE);
                PhotosView.this.setVisibility(GONE);
                // photosAdapter.notifyItemRangeRemoved(0, imageMessageList.size());
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    public Info getSmallImageInfo(int position) {

        if (onPageChangeListener != null) {
            return onPageChangeListener.onGetImageRectInfo(position);

            //showBigImageViewPagerAdapter.setInfoMap(currentInfoMap);
        }
        return null;
    }


    public void showBigImage(Info info, int position) {
        recyclerViewScroll = true;
        photosAdapter.notifyDataSetChanged();
        rl_photos.scrollToPosition(position);
        photosAdapter.setFromInfo(info);
        setStatusOfShowBigImage(true);
        setVisibility(VISIBLE);
        iv_blackBackGround.setVisibility(View.VISIBLE);
        //   postDelayed(() -> iv_blackBackGround.startAnimation(in), 100);
        iv_blackBackGround.startAnimation(in);
    }

    public void hideBigImage() {
        setStatusOfShowBigImage(false);
        iv_blackBackGround.startAnimation(out);
    }

    public boolean isHadSetData() {
        return hadSetData;
    }

    public void setStatusOfShowBigImage(boolean statusOfShowBigImage) {
        this.statusOfShowBigImage = statusOfShowBigImage;
    }


    public boolean onBackPressed() {
        if (statusOfShowBigImage) {
            recyclerViewScroll = false;
            Log.d(TAG, "onBackPressed: 子View 数量" + rl_photos.getChildCount());
            View child = rl_photos.getChildAt(0);
            PhotoView photoView = child.findViewById(R.id.iv_picture);
            int position = rl_photos.getChildAdapterPosition(child);
            Log.d(TAG, "onBackPressed: AdapterPosition" + position);
            if (position != -1) {//-1 表示没有找到 对应的位置，此刻的 snapView 并不是当前显示到页面上的View

                //想仅对 缩小了的item 设置 不可复用，但是 偶尔还是会出现大图位置显示错位，暂时全部设置为 不可复用
//                RecyclerView.ViewHolder childViewHolder = rl_photos.getChildViewHolder(child);
//                childViewHolder.setIsRecyclable(false);
                Info imageInfo = getSmallImageInfo(position);
                if (imageInfo != null) {
                    photosAdapter.bigImageAnimateOut(imageInfo, photoView);
                } else {
                    Log.e(TAG, "onBackPressed: 获取小图消息失败 position：" + position);
                }
            }

            hideBigImage();
            return false;
        } else {
            return true;
        }
    }

    public interface InteractionListener {
        void onPageChange(int position);

        Info onGetImageRectInfo(int position);
    }
}
